/**
 * 
 */
package com.swg.cocobox.client;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.swg.cocobox.KeyChange;

/**
 * @author satriaprayoga
 *
 */
public abstract class WriterClient extends Client {
	
	protected Map<SocketChannel, List<ByteBuffer>> pendingData;
	
	public WriterClient() throws IOException {
		super();
		this.pendingData=new HashMap<SocketChannel, List<ByteBuffer>>();
	}
	
	@Override
	public void run() {
		while(true){
			try {
				synchronized (keyChanges) {
					Iterator<KeyChange> keyIterator=keyChanges.iterator();
					while(keyIterator.hasNext()){
						KeyChange kc=keyIterator.next();
						switch (kc.getType()) {
						case KeyChange.CHANGE:
							SelectionKey key=kc.getChannel().keyFor(selector);
							key.interestOps(kc.getOperation());
							break;
						case KeyChange.REGISTER:
							kc.getChannel().register(selector, kc.getOperation());
							break;
						}
					}
					keyChanges.clear();
				}
				selector.select();
				Iterator<SelectionKey> selectedKeys=selector.selectedKeys().iterator();
				while(selectedKeys.hasNext()){
					SelectionKey key=selectedKeys.next();
					selectedKeys.remove();
					if(!key.isValid()){
						continue;
					}
					if(key.isConnectable()){
						finishConnection(key);
					}else if(key.isWritable()){
						write(key);
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	protected void write(SelectionKey key)throws IOException{
		SocketChannel socketChannel = (SocketChannel) key.channel();
		synchronized (pendingData) {
			List<ByteBuffer> queue = pendingData.get(socketChannel);
			while (!queue.isEmpty()) {
				ByteBuffer buf = (ByteBuffer) queue.get(0);
				socketChannel.write(buf);
				if (buf.remaining() > 0) {
					break;
				}
				queue.remove(0);
			}

			if (queue.isEmpty()) {
				socketChannel.close();
				socketChannel.keyFor(selector).cancel();
			}
		}
	}
	
	protected SocketChannel initConnection(InetAddress address,int port)throws IOException{
		SocketChannel channel=SocketChannel.open();
		channel.configureBlocking(false);
		channel.connect(new InetSocketAddress(address, port));
		synchronized (keyChanges) {
			keyChanges.add(new KeyChange(channel, KeyChange.REGISTER, SelectionKey.OP_CONNECT));
		}
		return channel;
	}
	
	@Override
	public void startClient() {
		// TODO Auto-generated method stub
		
	}

}
